package telas;

import inicio.Principal;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import servidor.InterfaceServicos;
import utilidades.ManipulaArquivos;

/**
 * 
 * @author Douglas Borges
 * 
 */
@SuppressWarnings("serial")
public class UsuarioI extends JPanel {

	public JTextArea caExecucao;

	@SuppressWarnings("unused")
	private JButton abrirArquivo, limparArquivo, btExecutar, btEncerrar, ajuda;

	private JComboBox cbArquitetura, cbCuda, cbOpnecl, cbC;

	private JCheckBox jcEdit;

	List<File> arquivos;

	private HashMap<String, File> mapFile = new HashMap<String, File>();

	private Image i;

	private JLabel label;

	List<String> listNomeLinha, listEquipe, listIdentificacaoExterna,
			listLocalArmazenado;

	JPanel painelArquitura = new JPanel();
	JPanel painelExemplos = new JPanel();
	JPanel painelExecucao = new JPanel();

	JButton bted1, bted2, bted3;

	Dimension screenSize = this.getToolkit().getScreenSize();
	double largura = screenSize.getWidth();
	double altura = screenSize.getHeight();

	int x = 0, y = 0;
	int remX = 0, remY = 0;//
	int painelExecucaoX = 0, painelExecucaoY = 370;//
	int painelArquivoX = 0, painelArquivoY = 210;//

	public UsuarioI() {

		super.setLayout(null);

		desenhaPainelArquitetura();// Desenha o painel com os objetos da
									// arquitetura

		desenhaPainelExemplo();// Desenha no Frame os Objetos de Survey

		desenhaPainelExecucao();// Desenha no Frame os Objetos de Survey

		super.setLocation(0, 0);
		super.setSize(screenSize);
		super.setVisible(true);

	}

	public void desenhaPainelExecucao() {

		painelExecucao.setLayout(null);
		painelExecucao.setBorder(BorderFactory
				.createTitledBorder("Executar o(s) Código(s)"));

		i = Toolkit.getDefaultToolkit().createImage(
				this.getClass().getResource("/imagens/play.jpg"));
		ImageIcon ii = new ImageIcon(i);

		btExecutar = new JButton(ii);
		btExecutar.setBounds(x + 10, y + 40, 50, 50);
		btExecutar.setName("executar");
		btExecutar.setToolTipText("Enviar ao Servidor");
		btExecutar.addActionListener(new ComandoBotoes());
		painelExecucao.add(btExecutar);

		i = Toolkit.getDefaultToolkit().createImage(
				this.getClass().getResource("/imagens/stop.jpg"));
		ii = new ImageIcon(i);

		btEncerrar = new JButton(ii);
		btEncerrar.setBounds(x + 10, y + 95, 50, 50);
		btEncerrar.setName("encerrar");
		btEncerrar.setToolTipText("Parar Execução");
		btEncerrar.addActionListener(new ComandoBotoes());
		painelExecucao.add(btEncerrar);

		caExecucao = new JTextArea();
		caExecucao.setBounds(x + 65, y + 30, (int) (largura * 0.50),
				(int) (altura * 0.25));
		caExecucao.setEditable(false);

		JScrollPane scroll = new JScrollPane(caExecucao);
		scroll.setBounds(x + 65, y + 30, (int) (largura * 0.50),
				(int) (altura * 0.25));
		painelExecucao.add(scroll);

		painelExecucao.setBounds(painelExecucaoX, painelExecucaoY,
				(int) ((largura) * 0.50) + 70, (int) (altura * 0.32));

		super.add(painelExecucao);
		super.repaint();
		super.revalidate();

	}

	@SuppressWarnings("static-access")
	public void desenhaPainelExemplo() {

		painelExemplos.setLayout(null);

		painelExemplos
				.setBorder(BorderFactory
						.createTitledBorder("Exemplos de Aplicações desenvolvidas em C, CUDA e OpenCL"));

		try {
			System.out.println(Principal.exemplo);
			arquivos = ManipulaArquivos.getInstance().listFiles(
					new File(Principal.exemplo), true);
		} catch (Exception e) {
			e.printStackTrace();
		}

		jcEdit = new JCheckBox("Editar Código");
		jcEdit.setSelected(false);
		jcEdit.setBounds(10, 20, 300, 20);
		painelExemplos.add(jcEdit);
		int xC = 10, xCuda = 500, xOpenCL = 950, yC = 40, yCuda = 40, yOpencl = 40;

		preencheCheckBoxcCres(xC, yC, xCuda, yCuda, xOpenCL, yOpencl);

		painelExemplos.setBounds(painelArquivoX, painelArquivoY,
				(int) ((largura) * 0.98), 150);

		super.add(painelExemplos);
		this.repaint();
		this.revalidate();

	}

	private void preencheCheckBoxcCres(Integer xC, Integer yC, Integer xCuda,
			Integer yCuda, Integer xOpenCL, Integer yOpenCL) {

		label = new JLabel("Exemplos em C:");
		label.setBounds(xC, yC, 200, 20);
		painelExemplos.add(label);

		label = new JLabel("Exemplos em CUDA:");
		label.setBounds(xCuda, yCuda, 200, 20);
		painelExemplos.add(label);

		label = new JLabel("Exemplos em OpenCL:");
		label.setBounds(xOpenCL, yOpenCL, 200, 20);
		painelExemplos.add(label);

		cbC = new JComboBox();
		for (int i = 0; i < arquivos.size(); i++) {
			File f = arquivos.get(i);
			if (f.getAbsolutePath().toLowerCase()
					.contains(File.separator + "c" + File.separator)
					&& !f.getAbsolutePath().toLowerCase().contains(".ds_store")) {
				if (f.getName().endsWith(".c") || f.getName().endsWith(".cpp")) {
					cbC.addItem(f.getName().toUpperCase().replaceAll("_", " "));
					mapFile.put(f.getName().toUpperCase().replaceAll("_", " "),
							f);
				}
			}
		}
		cbC.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (jcEdit.isSelected())
					new EditarCodigo(mapFile.get(cbC.getSelectedItem()));
			}
		});
		cbC.setEnabled(false);
		cbC.setBounds(xC, yC + 30, 350, 45);
		painelExemplos.add(cbC);

		cbCuda = new JComboBox();
		for (int i = 0; i < arquivos.size(); i++) {
			File f = arquivos.get(i);
			if (f.getAbsolutePath().toLowerCase()
					.contains(File.separator + "cuda" + File.separator)
					&& !f.getAbsolutePath().toLowerCase().contains(".ds_store")) {
				if (f.getName().endsWith(".cu") || f.getName().endsWith(".cpp")
						|| f.getName().endsWith(".c")) {
					cbCuda.addItem(f.getName().toUpperCase()
							.replaceAll("_", " "));
					mapFile.put(f.getName().toUpperCase().replaceAll("_", " "),
							f);
				}

			}
		}
		cbCuda.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (jcEdit.isSelected())
					new EditarCodigo(mapFile.get(cbCuda.getSelectedItem()));
			}
		});
		cbCuda.setEnabled(false);
		cbCuda.setBounds(xCuda, yCuda + 30, 350, 45);
		painelExemplos.add(cbCuda);

		cbOpnecl = new JComboBox();
		for (int i = 0; i < arquivos.size(); i++) {
			File f = arquivos.get(i);
			if (f.getAbsolutePath().toLowerCase()
					.contains(File.separator + "opencl" + File.separator)
					&& !f.getAbsolutePath().toLowerCase().contains(".ds_store")) {
				if (f.getName().endsWith(".c") || f.getName().endsWith(".cpp")
						|| f.getName().endsWith(".cl")) {
					cbOpnecl.addItem(f.getName().toUpperCase()
							.replaceAll("_", " "));
					mapFile.put(f.getName().toUpperCase().replaceAll("_", " "),
							f);
				}
			}
			cbOpnecl.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					if (jcEdit.isSelected())
						new EditarCodigo(
								mapFile.get(cbOpnecl.getSelectedItem()));
				}
			});
			cbOpnecl.setEnabled(false);
			cbOpnecl.setBounds(xOpenCL, yOpenCL + 30, 350, 45);
			painelExemplos.add(cbOpnecl);
		}

	}

	public void desenhaPainelArquitetura() {

		painelArquitura.setLayout(null);
		painelArquitura
				.setBorder(BorderFactory
						.createTitledBorder("Selecione a arquitetura que deseja executar"));

		cbArquitetura = new JComboBox();
		cbArquitetura.setBorder(BorderFactory.createTitledBorder("Linguagem"));
		cbArquitetura.setBounds(x + 10, y + 30, (int) ((largura / 2) * 0.40),
				45);
		cbArquitetura.addItem("Linguagem C");
		cbArquitetura.addItem("Arquitetura CUDA");
		cbArquitetura.addItem("Arquitetura OpenCL");

		cbArquitetura.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				if (cbArquitetura.getSelectedIndex() == 0) {
					cbC.setEnabled(true);
					cbCuda.setEnabled(false);
					cbOpnecl.setEnabled(false);
				}
				if (cbArquitetura.getSelectedIndex() == 1) {
					cbC.setEnabled(false);
					cbCuda.setEnabled(true);
					cbOpnecl.setEnabled(false);
				}
				if (cbArquitetura.getSelectedIndex() == 2) {
					cbC.setEnabled(false);
					cbCuda.setEnabled(false);
					cbOpnecl.setEnabled(true);
				}

			}
		});
		painelArquitura.add(cbArquitetura);

		int posicaoX = (int) ((largura / 2) * 0.40);
		i = Toolkit.getDefaultToolkit().createImage(
				this.getClass().getResource("/imagens/lingc.jpg"));
		ImageIcon ii = new ImageIcon(i);
		label = new JLabel(ii);
		label.setToolTipText("Linguagem C");
		label.setBounds(x + posicaoX + 20, y + 20, 100, 100);
		painelArquitura.add(label);

		i = Toolkit.getDefaultToolkit().createImage(
				this.getClass().getResource("/imagens/cuda.jpg"));
		ii = new ImageIcon(i);
		label = new JLabel(ii);
		label.setToolTipText("Arquitetura CUDA");
		label.setBounds(x + posicaoX + 125, y + 20, 100, 100);
		painelArquitura.add(label);

		i = Toolkit.getDefaultToolkit().createImage(
				this.getClass().getResource("/imagens/opencl.jpg"));
		ii = new ImageIcon(i);
		label = new JLabel(ii);
		label.setToolTipText("Arquitetura OpenCL");
		label.setBounds(x + posicaoX + 230, y + 20, 100, 100);

		painelArquitura.add(label);

		painelArquitura.setBounds(remX, remY, (int) (largura * 0.98), 190);

		super.add(painelArquitura);
		this.repaint();
		this.revalidate();

	}

	private class ComandoBotoes implements ActionListener {
		public void actionPerformed(ActionEvent evento) {

			String nomeBt = (((JButton) ((Object) evento.getSource()))
					.getName());
			caExecucao.setText("");

			if (nomeBt.equals("executar")) {

				try {
					if (cbArquitetura.getSelectedIndex() == 0
							&& !jcEdit.isSelected()) {
						File f = mapFile.get(cbC.getSelectedItem());
						caExecucao.setText(cbC.getSelectedItem() + "");
						InterfaceServicos it = getInterfaceServicos();
						caExecucao.setText(it.executeC("GPUHelp-"
								+ Principal.macEndereco, getFile(f)));
					} else if (cbArquitetura.getSelectedIndex() == 0
							&& jcEdit.isSelected()) {
						File f = new File(Principal.diretorioUsuario + "/"
								+ Principal.pastaTrabalho + "/"
								+ mapFile.get(cbC.getSelectedItem()).getName());
						caExecucao.setText(cbC.getSelectedItem() + "");
						InterfaceServicos it = getInterfaceServicos();
						caExecucao.setText(it.executeC("GPUHelp-"
								+ Principal.macEndereco, getFile(f)));
					}

					else if (cbArquitetura.getSelectedIndex() == 1
							&& !jcEdit.isSelected()) {
						File f = mapFile.get(cbCuda.getSelectedItem());
						caExecucao.setText(cbCuda.getSelectedItem() + "");
						InterfaceServicos it = getInterfaceServicos();
						caExecucao.setText(it.executeCuda("GPUHelp-"
								+ Principal.macEndereco, getFile(f)));

					} else if (cbArquitetura.getSelectedIndex() == 1
							&& jcEdit.isSelected()) {
						File f = new File(Principal.diretorioUsuario
								+ "/"
								+ Principal.pastaTrabalho
								+ "/"
								+ mapFile.get(cbCuda.getSelectedItem())
										.getName());

						caExecucao.setText(cbCuda.getSelectedItem() + "");
						InterfaceServicos it = getInterfaceServicos();
						caExecucao.setText(it.executeCuda("GPUHelp-"
								+ Principal.macEndereco, getFile(f)));
					} else if (cbArquitetura.getSelectedIndex() == 2
							&& !jcEdit.isSelected()) {
						File f = mapFile.get(cbOpnecl.getSelectedItem());
						caExecucao.setText(cbOpnecl.getSelectedItem() + "");
						InterfaceServicos it = getInterfaceServicos();
						caExecucao.setText(it.executeOpencl("GPUHelp-"
								+ Principal.macEndereco, getFile(f)));

					} else if (cbArquitetura.getSelectedIndex() == 2
							&& jcEdit.isSelected()) {
						File f = new File(Principal.diretorioUsuario
								+ "/"
								+ Principal.pastaTrabalho
								+ "/"
								+ mapFile.get(cbOpnecl.getSelectedItem())
										.getName());
						caExecucao.setText(cbOpnecl.getSelectedItem() + "");
						InterfaceServicos it = getInterfaceServicos();
						caExecucao.setText(it.executeOpencl("GPUHelp-"
								+ Principal.macEndereco, getFile(f)));
					}

				}

				catch (Exception e) {
					e.printStackTrace();
					System.out.println("ERRO");
				}

			}
			if (nomeBt.equals("parar")) {
				jcEdit.setSelected(false);
				caExecucao.setText("");
			}

		}
	}

	public StringBuilder getFile(File f) {
		StringBuilder sb = new StringBuilder();
		try {
			Scanner in = new Scanner(f);
			sb.append("//" + f.getName() + "\n");
			while (in.hasNextLine()) {
				sb.append(in.nextLine()).append("\n");
			}
			in.close();

		}

		catch (Exception e) {

			System.out.println(e.getMessage());
		}
		return sb;
	}

	private final InterfaceServicos getInterfaceServicos() {
		try {
			Registry registry = LocateRegistry
					.getRegistry(Principal.ipServidor);
			InterfaceServicos servicosRemotos = (InterfaceServicos) registry
					.lookup(Principal.servidor);
			System.out.println(servicosRemotos.getStatus(Principal.macEndereco,
					Principal.usuario));
			return servicosRemotos;
		} catch (Exception e) {

			e.printStackTrace();
		}
		return null;
	}

	public void setExecucao(String exe) {
		caExecucao.setText(exe);
	}

}